package com.example.demo.getListAPP;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.ComponentName;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ListView;
import android.widget.TextView;

import com.example.demo.R;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class ListAppActivity extends AppCompatActivity {
    private String Tag = "ListAppActivity";

    private RecyclerView recyclerView;
    private ListAdapter mAdapter;
    private List<String> list;

    private Drawable appIcon;
    private ApplicationInfo appInfo;

    private TextView text;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_app);
        initView();
    }

    private void initView(){
        recyclerView = findViewById(R.id.list);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

       List<IconBean> bean = getAppIconName(getPkgList());
//        List<IconBean> bean = getAppIconName(getPkgListNew());
        mAdapter = new ListAdapter(bean,this);
        recyclerView.setAdapter(mAdapter);

        text = findViewById(R.id.text);
        text.setText("总共"+bean.size()+"个APP");

        Log.i(Tag,""+getPkgList().size());
        Log.i(Tag,getPkgList().toString());

        Log.i(Tag,""+getPkgListNew().size());
        Log.i(Tag,getPkgListNew().toString());
    }


    /**
     * 获取所有应用列表（系统应用+非系统应用）
     * shell 命令
     * @return
     */
    private List<String> getPkgList() {
        List<String> packages = new ArrayList<String>();
        try {
            Process p = Runtime.getRuntime().exec("pm list packages");
            InputStreamReader isr = new InputStreamReader(p.getInputStream(), "utf-8");
            BufferedReader br = new BufferedReader(isr);
            String line = br.readLine();
            while (line != null) {
                line = line.trim();
                if (line.length() > 8) {
                    String prefix = line.substring(0, 8);
                    if (prefix.equalsIgnoreCase("package:")) {
                        line = line.substring(8).trim();
                        if (!TextUtils.isEmpty(line)) {
                            packages.add(line);
                        }
                    }
                }
                line = br.readLine();
            }
            br.close();
            p.destroy();
        } catch (Throwable t) {
            t.printStackTrace();
        }
        return packages;
    }

    /**
     * 获取所有应用列表（系统应用+非系统应用）
     * @return
     */
    private List<String> getPkgListNew() {
        List<String> packages = new ArrayList<String>();
        try {
            List<PackageInfo> packageInfos = getApplication().getPackageManager().getInstalledPackages(PackageManager.GET_ACTIVITIES | PackageManager.GET_SERVICES);
            for (PackageInfo info : packageInfos) {
                String pkg = info.packageName;
                isSystemApp(info);
                packages.add(pkg);
            }
        } catch (Throwable t) {
            t.printStackTrace();;
        }
        return packages;
    }


    // 通过packName得到PackageInfo，作为参数传入即可
    private boolean isSystemApp(PackageInfo pi) {
        boolean isSysApp = (pi.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 1;
        boolean isSysUpd = (pi.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) == 1;
        return isSysApp || isSysUpd;
    }


    private List<IconBean> getAppIconName(List<String> list){
        List<IconBean> Listbean = new ArrayList<>();
        PackageManager pm = getPackageManager();
        for (String pakgename:list){
            IconBean bean = new IconBean();
            try {
                appInfo = pm.getApplicationInfo(pakgename, PackageManager.GET_META_DATA);
                boolean bo =  isSystemApp(pm.getPackageInfo(pakgename,0));
                bean.setSystemApp(bo);
                // 应用名称
                bean.setAppName((String) pm.getApplicationLabel(appInfo)) ;
                //应用图标
               bean.setAppIcon(appIcon = pm.getApplicationIcon(appInfo));
               if(!bo){//不是系统应用添加
                   Listbean.add(bean);
               }
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
        }
        return Listbean;
    }



}
